package com.heima.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dto.ArticleDto;
import com.heima.model.article.dto.ArticleHomeDto;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApArticleContent;
import com.heima.model.article.pojos.ApArticleConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.heima.common.constants.ArticleConstants.*;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static int MAX_PAGE_SIZE = 50;
    // 单页最小加载的数字
    private final static int MIN_PAGE_SIZE = 10;

    @Resource
    private ApArticleMapper apArticleMapper;

    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult<List<ApArticle>> load(Short loadtype, ArticleHomeDto dto) {
        //1.校验参数
        int size = Convert.toInt(dto.getSize(), MIN_PAGE_SIZE);
        size = Math.max(size, MIN_PAGE_SIZE);
        size = Math.max(size, MAX_PAGE_SIZE);
        dto.setSize(size);
//        类型参数校验。
        if(ObjectUtil.notEqual(loadtype,LOADTYPE_LOAD_MORE)&& ObjectUtil.notEqual(loadtype,LOADTYPE_LOAD_NEW)){
            loadtype = LOADTYPE_LOAD_MORE;
        }

//      频道校验。
        if(StrUtil.isEmpty(dto.getTag())){
            dto.setTag(DEFAULT_TAG);
        }
//        时间校验
        if(ObjectUtil.isEmpty(dto.getMaxBehotTime())){
            dto.setMaxBehotTime(new Date());
        }

        if(ObjectUtil.isEmpty(dto.getMinBehotTime())){
            dto.setMinBehotTime(new Date());
        }
//        查询结果。
        List<ApArticle> apArticles = this.apArticleMapper.loadArticleList(dto, loadtype);

//        apArticles.forEach(apArticle -> {
//            try {
//                this.uploadFile(apArticle.getId());
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//        });

        return ResponseResult.okResult(apArticles);
    }

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto articleDto) {
//        对传来的参数进行校验
        if(ObjectUtil.isEmpty(articleDto)){
            return  ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        ApArticle apArticle = BeanUtil.toBean(articleDto, ApArticle.class);
//       判断是新增还是 修改。根据id
        if(ObjectUtil.isEmpty(articleDto.getId())){
//            走新增
//            新增文章表
            super.save(apArticle);
//            新增配置表
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            this.apArticleConfigMapper.insert(apArticleConfig);
//            新增内容表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(articleDto.getContent());
            this.apArticleContentMapper.insert(apArticleContent);

        }else{
//            修改。
//            修改文章表
            super.updateById(apArticle);
//            修改内容表。
            LambdaQueryWrapper<ApArticleContent> wrapper = Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getId());
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(wrapper);
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        return ResponseResult.okResult(apArticle.getId());
    }


    private void uploadFile(Long articleId) throws IOException, TemplateException {
        //1.获取文章内容
        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleId));
        if (ObjectUtil.isEmpty(apArticleContent)) {
            System.out.println("没有查询到文章内容数据");
        }

        //2.文章内容通过freemarker生成html文件
        StringWriter out = new StringWriter();
        Template template = configuration.getTemplate("article.ftl");

        Map<String, Object> params = new HashMap<>();
        params.put("content", JSONArray.parseArray(apArticleContent.getContent()));

        template.process(params, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());

        //3.把html文件上传到minio中
        String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

        //4.修改ap_article表，保存static_url字段
        ApArticle article = new ApArticle();
        article.setId(apArticleContent.getArticleId());
        article.setStaticUrl(path);
        apArticleMapper.updateById(article);

        System.out.println("上传成功：" + path);
    }

}
